mongodb+srv://<username>:<password>@cluster0.xxxxx.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0
Step 3: Add the connection string to environment variables.env.local
file.
MONGODB_URI=mongodb+srv://<username>:<password>@cluster0.xxxxx.mongodb.net/myDatabase?retryWrites=true&w=majority&appName=Cluster0
Step 4: Get username and passwordapp/
), create a file lib/mongodb.js
or utils/mongodb.js
// lib/mongodb.js
import { MongoClient } from 'mongodb'
const uri = process.env.MONGODB_URIconst options = { useNewUrlParser: true,}
let clientlet clientPromise
if (!process.env.MONGODB_URI) { throw new Error('Add Mongo URI to .env.local')}
if (process.env.NODE_ENV === 'development') { if (!global._mongoClientPromise) { client = new MongoClient(uri, options) global._mongoClientPromise = client.connect() } clientPromise = global._mongoClientPromise} else { client = new MongoClient(uri, options) clientPromise = client.connect()}
export default clientPromise
app/api/add/route.js
, you can now do: import clientPromise from "@/lib/mongodb";import { NextResponse } from "next/server";
export async function POST(request) { const body = await request.json(); const client = await clientPromise; const db = client.db("Blogs"); const collection = db.collection("Blog");
const doc = await collection.findOne({ title: body.title });
if (doc) { return NextResponse.json({ success: false, error: true, message: 'This Title already exists', result: null }); }
const result = await collection.insertOne(body);
return NextResponse.json({ success: true, error: false, message: 'Your Blog has been Published', result: result });}
export async function GET(request) { const client = await clientPromise; const db = client.db("Blogs"); const collection = db.collection("Blog");
const blogs = await collection.find().toArray();
// console.log(blogs); return NextResponse.json(blogs);}
• The POST function will be accessed for POST req and GET function will be accessed for GET req. const handleSave = async (title) => { const content = document.getElementById("editor").innerHTML;
await fetch("/api/add", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ title: title, html: content }), }); toast("Successfully Published") redirect("/all") };